package com.wolfheader.wolfgame.controller.admin;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.plaf.synth.SynthSeparatorUI;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.aliyun.common.utils.Lists;
import com.wolfheader.wolfgame.Message;
import com.wolfheader.wolfgame.bean.admin.AdminBean;
import com.wolfheader.wolfgame.bean.admin.AdminModifBean;
import com.wolfheader.wolfgame.controller.BaseController;
import com.wolfheader.wolfgame.dao.admin.AdminDao;
import com.wolfheader.wolfgame.dao.admin.RoleDao;
import com.wolfheader.wolfgame.entity.admin.AdminEntity;
import com.wolfheader.wolfgame.entity.admin.RoleEntity;
import com.wolfheader.wolfgame.service.GameRecordService;
import com.wolfheader.wolfgame.service.admin.AdminService;
import com.wolfheader.wolfgame.util.JqDataTabelUtils;

@Controller
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

	@Autowired
	private AdminDao adminDao;

	@Resource(name = "adminServiceImpl")
	private AdminService adminService;

	@Autowired
	private RoleDao roleDao;

	@Resource(name = "gameRecordServiceImpl")
	private GameRecordService gameRecordService;

	private static final String template_url = "admin/admin";

	private static final String INDEX_REDIRECT_URL = "redirect:/admin/admin";

	@RequestMapping(method = RequestMethod.GET)
	public String admin(HttpServletRequest request, ModelMap map) {
		return "redirect:admin/login";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String login(HttpServletRequest request, ModelMap map) {
		map.addAttribute("menu1", "admin");
		map.addAttribute("menu2", "list");
		return template_url + "/list";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(HttpServletRequest request, ModelMap map) {
		map.addAttribute("menu1", "admin");
		map.addAttribute("menu2", "add");
		map.addAttribute("roles", roleDao.findAll());
		return template_url + "/add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@Validated AdminBean bean, HttpServletRequest request, RedirectAttributes attr) {
		adminService.add(bean);
		addFlashMessage(attr, Message.success("添加成功"));
		return INDEX_REDIRECT_URL + "/list";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@PathVariable Long id, @Validated AdminModifBean admin, RedirectAttributes redirectAttributes) {
		// Bean Validation
		if (!verify(admin)) {
			addFlashMessage(redirectAttributes, Message.error("参数错误"));
			return INDEX_REDIRECT_URL + "/edit/{id}";
		}
		// 验证管理员是否存在
		AdminEntity pAdmin = adminDao.findOne(id);
		if (pAdmin == null) {
			addFlashMessage(redirectAttributes, Message.error("管理员验证失败"));
			return INDEX_REDIRECT_URL + "/list";
		}
		Set<RoleEntity> roleEntitys = new HashSet<RoleEntity>();
		for (Long rid : admin.getRoles()) {
			roleEntitys.add(roleDao.findOne(rid));
		}
		pAdmin.setRoles(roleEntitys);
		pAdmin.setEnabled(admin.getEnabled());
		pAdmin.setIdNo(admin.getIdNo());
		pAdmin.setPhone(admin.getPhone());
		pAdmin.setRealName(admin.getRealName());
		pAdmin.setWxName(admin.getWxName());
		// 修改密码时
		if (StringUtils.isNotBlank(admin.getPassword())) {
			// 设置新密码MD5加密
			pAdmin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		}
		adminDao.save(pAdmin);
		addFlashMessage(redirectAttributes, Message.success("管理员修改成功"));
		return INDEX_REDIRECT_URL + "/list";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable Long id, HttpServletRequest request, RedirectAttributes attr,
			ModelMap map) {
		AdminEntity admin = adminDao.findOne(id);
		if (admin == null) {
			addFlashMessage(attr, Message.error("管理员不存在"));
			return INDEX_REDIRECT_URL + "/list";
		}
		List<RoleEntity> list = Lists.newLinkedList(roleDao.findAll());
		List<RoleEntity> myList = Lists.newLinkedList(admin.getRoles());
		for (int i = 0; i < list.size(); i++) {
			if (myList.contains(list.get(i))) {
				list.remove(i);
			}
		}
		map.addAttribute("myList", myList);
		map.addAttribute("roles", list);
		map.addAttribute("admin", admin);
		map.addAttribute("menu1", "admin");
		map.addAttribute("menu2", "list");
		map.addAttribute("editId", id);
		return template_url + "/edit";
	}

	/**
	 * 管理员列表分页
	 * 
	 * @param request
	 * @param sEcho
	 * @param iDisplayStart
	 * @param iDisplayLength
	 * @param sSearch
	 * @return
	 */
	@RequestMapping(value = "/getData", method = RequestMethod.POST)
	public @ResponseBody String getData(HttpServletRequest request, @RequestParam String sEcho,
			@RequestParam Integer iDisplayStart, @RequestParam Integer iDisplayLength,
			@RequestParam final String sSearch) {
		Sort sort = new Sort(Direction.DESC, "id");
		Page<AdminEntity> page = null;
		if (sSearch == null || sSearch.equals("null")) {
			page = adminService.findAll("", new PageRequest(iDisplayStart, iDisplayLength, sort));
		} else {
			page = adminService.findAll(sSearch, new PageRequest(iDisplayStart, iDisplayLength, sort));
		}

		return JqDataTabelUtils.getDataTabelJson(page, iDisplayStart, sEcho);
	}

	@RequestMapping(value = "/checkname", method = RequestMethod.POST)
	public @ResponseBody Boolean checkname(@RequestParam String name) {
		return adminService.findUsernameEixst(name);
	}

}
